package com.byq.mm.smartlib.cluster.activity.client;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;


import com.byq.mm.abstractx.cluster.client.ClusterClient;
import com.byq.mm.abstractx.cluster.client.DeviceClient;
import com.byq.mm.abstractx.cluster.client.event.ClusterChangeEvent;
import com.byq.mm.smartlib.SmartActionConstants;
import com.byq.mm.smartlib.activity.AbstractSmartActivity;

public abstract class ClientClusterActivity<T extends ClusterClient> extends AbstractSmartActivity {

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(updateReceiver);
	}
	protected T client;
	private BroadcastReceiver updateReceiver;
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		String globalId = this.getIntent().getExtras().getString("globalId");
		DeviceClient device = application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager().getDeviceClient(globalId);
		String clusterId = this.getIntent().getExtras().getString("clusterId");
		
		client = (T)device.getClusterClient(clusterId);
		
		updateReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String globalId = intent.getExtras().getString("globalId");
				String clusterId = intent.getExtras().getString("clusterId");
				ClusterChangeEvent e = (ClusterChangeEvent)intent.getExtras().get("event");
				if(globalId.equals(client.getDevice().getGlobalId()) && clusterId.equals(client.getCluster())){
					update(e);
					
					application.getSound().playSound(0);
				}
			}

		
		};

		IntentFilter listFilter =  new IntentFilter();
		listFilter.addAction(SmartActionConstants.CLUSTER_CLIENT_UPDATED);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			registerReceiver(updateReceiver, listFilter, RECEIVER_NOT_EXPORTED);
		}

	
	}
	protected abstract void update(ClusterChangeEvent e);
}
